var MSG = {
		ERR:"系统错误，请刷新重试或联系管理员！"
		, TO_PRINTER:"内容已输出至打印机！"
};
// 自动填入年份连接符
function autoInputTime(id) {
	$("#" + id).keyup(function(event) {
		if(event.keyCode!=KEY.BACKSPACE) {
			var len = $(this).val().length;
			var val = $(this).val()+'-';
			switch(len) {
			case 4:
				$(this).val(val);
			case 7:
				$(this).val(val);
			}
		}
	});
}

// 关于村庄的筛选
function Village() {
	var dt, bg, _this, visible=false;
	_this = this;
	// 隱藏篩選列表
	this.hide = function() {
		aju.removeAll([ dt, bg, $('.tip-yellow') ]);
		$('#ajaxClose').remove();
		visible = false;
	};
	// 顯示村莊的篩選列表
	this.show = function() {
		if(visible) {
			return dt;
		}
		bg = aju.ajaxBg(function() {
			aju.setOffsetDown(20);
			aju.setOffsetRight(10);
			var url = '/a/ajax/sell/villageList/?r=' + new Date();
			$.get(url, function(data){
					dt = aju.ajaxData().css('width','980');
					dt.html(data);
					aju.positionCenter(dt);
					aju.ajaxClose(dt).click(function(){
						_this.hide();
					});
					_this.bindEvent();
			});
		});
		$('body').keydown(function(event){
			switch(event.keyCode) {
			case KEY.ESC :
				_this.hide();
			}
		});
		visible = true;
	};
	this.bindEvent = function() {
		var kw = dt.find('input[type=text]:first');
		kw.focus();
		dt.find('button:first').bind('click', function(){
			_this.search(kw.val());
		}).next().bind('click', function(){
			_this.search('');
		});
		kw.keydown(function(event){
			switch(event.keyCode) {
			case KEY.ENTER :
				_this.search(kw.val());
			}
		});
		choiceVillageEvent();
	};
	var searching = false;
	this.search = function(kw) {
		if(searching) {
			return ;
		}
		searching = true;
		dt.find('dl').remove();
		dt.find('em').remove();
		var loading = $("<div>筛选中...请稍候...</div>")
			.css({'margin':'7px', 'color':'#ff0000'})
			.attr('id','vl');
		dt.append(loading);
		$.get('/a/ajax/sell/villageFilter/?r=' + new Date() + "&q=" + kw, function(data){
			$('#vl').remove();
			dt.append(data);
			choiceVillageEvent();
			searching = false;
		});
	};
	// 绑定点击事件
	function choiceVillageEvent() {
		dt.find("dd").bind('click', function() {
			var id = $(this).attr('id');
			//alert(id);
			$.get('/a/ajax/sell/village-' + id, function(data){
				var json = $.parseJSON(data);
				$("#villageSelector").html(json.data.town.name + " " + json.data.village.name);
				$("#villageId").val(id);
				_this.hide();
			});
		});
	};
}
var village = new Village();
/**/
$(document).ready(function() {  
	   $("a[rel='external']").click(function(){  
	      this.target = "_blank";  
	   });
	   jQuery.fn.center = function () {  
			this.css("position","absolute");  
			this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");  
			this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");  
			return this;  
		}  
}); 
/**/
$(function($){
	$.datepicker.regional['zh-CN'] = {
		closeText: '关闭',
		prevText: '&#x3c;上月',
		nextText: '下月&#x3e;',
		currentText: '今天',
		monthNames: ['一月','二月','三月','四月','五月','六月',
		'七月','八月','九月','十月','十一月','十二月'],
		monthNamesShort: ['一','二','三','四','五','六',
		'七','八','九','十','十一','十二'],
		dayNames: ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'],
		dayNamesShort: ['周日','周一','周二','周三','周四','周五','周六'],
		dayNamesMin: ['日','一','二','三','四','五','六'],
		weekHeader: '周',
		dateFormat: 'yy-mm-dd',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: true,
		yearSuffix: '年'};
	$.datepicker.setDefaults($.datepicker.regional['zh-CN']);
});
/* 控制导航下拉菜单 */
(function($) {
	$.fn.powerFloat = function(options) {
		return $(this).each(function() {
			var init = function(_s) {
				o.s = _s;
			};
			var s = $.extend({}, defaults, options || {});
			s.trigger = $(this);
			s.tip = $('<div class="tip-wrapper"><div class="tipsy-inner"/></div>'),
			init(s);
			switch(s.eventType) {
				case 'hover':
					$(this).hover(function() {					
						init(s, $(this));
						o.targetGet();
					}, function(){
						o.targetHold();
					});
				break;
			}
		});
	};
	var o = {
		flagDisplay: false,
		timerHold: null,
		targetGet: function() {
			if(!this.s.trigger) { return this; }
			this.flagDisplay = false;
			this.displayDetect();
			this.targetShow(); 	
		},
		setWidth: function() {
			this.s.tip.width(this.s.width);
		},
		setPosition: function() {
			var pos = this.s.trigger.offset();
			var tri_h = this.s.trigger.outerHeight(true);
			var tri_w = this.s.trigger.outerWidth(true);
			var tri_l = pos.left;
			var tri_t = pos.top;
			var tpos = this.s.tip.offset();
			var st = $(document).scrollTop();
			//alert(this.s.trigger.html());
			this.s.tip.css({
				top: (tri_t + tri_h - st)
				, left: tri_l
			})
		},
		targetHold: function() {
			if (this.s.tip) {
				this.s.tip.hover(function() {
					o.flagDisplay = true;
				}, function() {
					if(o.timerHold) {
						clearTimeout(o.timerHold);
					}
					o.flagDisplay = false; //标记可以隐藏
					o.targetHold();	
				});
			}
			o.timerHold = setTimeout(function() {
				o.displayDetect.call(o);
			}, o.s.hideDelay);
		},
		targetShow: function() {
			$(".tip-wrapper").remove();
			this.s.tip.first().html(this.s.html);
			$(document.body).append(this.s.tip);
			this.s.tip.css({
				'font-size': this.s.fontSize
			});
			this.setWidth();
			if(this.s.tip.hasClass('yyy_slt')) {
				this.s.tip.removeClass('yyy_tip');
				this.s.tip.addClass('yyy_slt');
			} else {
				this.s.tip.removeClass('yyy_slt');
				this.s.tip.addClass('yyy_tip');
			}
			if(this.s.triggerStyle) {
				$(this.s.trigger).addClass('yyy_slted');
				this.s.tip.find('a span').each(function(){
					$(this).hover(function(){
						$(this).addClass('a_hover');
					}, function(){
						$(this).removeClass('a_hover');
					});
				});
			}
			this.s.tip.css({
				zIndex: this.s.zIndex
			});
			this.s.tip.show();
			this.setPosition();
		},
		targetHide: function() {
			if(!this.flagDisplay) { // 可以隐藏
				$(this.s.trigger).removeClass('yyy_slted');
				this.s.tip.remove();
				this.flagDisplay = false;
			}
		},
		displayDetect: function() {
			//显示与否 检测与触发
			if (!this.flagDisplay) {
				this.targetHide();
				this.timerHold = null;
				this.flagDisplay = false;
			} else {
				
			}
			return this;
		},
		s:{}
	};
	//
	var defaults  = {
			width: "auto", //可选参数：inherit，数值(px)
			offsets: {
				x: 0,
				y: 0	
			},
			zIndex: 12,
			eventType: "hover", //事件类型，其他可选参数有：click, focus
			showDuration: 3,
			showDelay: 0, //鼠标hover显示延迟
			hideDelay: 1, //鼠标移出隐藏延时
			targetMode: "common", //浮动层的类型，其他可选参数有：ajax, list, remind
			target: null, //target对象获取来源，优先获取，如果为null，则从targetAttr中获取。
			targetAttr: "rel", //target对象获取来源，当targetMode为list时无效
			html: null,
			triggerStyle: true,
			fontSize: '12px'
	};
	
})(jQuery);
//
/** **/
(function($){
	$.fn.textSearch = function(str,options){
		var defaults = {
			divFlag: true,
			divStr: " ",
			markClass: "",
			markColor: "red",
			nullReport: true,
			callback: function(){
				return false;	
			}
		};
		var sets = $.extend({}, defaults, options || {}), clStr;
		if(sets.markClass){
			clStr = "class='"+sets.markClass+"'";	
		}else{
			clStr = "style='color:"+sets.markColor+";'";
		}
		//对前一次高亮处理的文字还原
		$("span[rel='mark']").removeAttr("class").removeAttr("style").removeAttr("rel");
		
		//字符串正则表达式关键字转化
		$.regTrim = function(s){
			var imp = /[\^\.\\\|\(\)\*\+\-\$\[\]\?]/g;
			var imp_c = {};
			imp_c["^"] = "\\^";
			imp_c["."] = "\\.";
			imp_c["\\"] = "\\\\";
			imp_c["|"] = "\\|";
			imp_c["("] = "\\(";
			imp_c[")"] = "\\)";
			imp_c["*"] = "\\*";
			imp_c["+"] = "\\+";
			imp_c["-"] = "\\-";
			imp_c["$"] = "\$";
			imp_c["["] = "\\[";
			imp_c["]"] = "\\]";
			imp_c["?"] = "\\?";
			s = s.replace(imp,function(o){
				return imp_c[o];					   
			});	
			return s;
		};
		$(this).each(function(){
			var t = $(this);
			str = $.trim(str);
			if(str === ""){
				//alert("关键字为空");	
				return false;
			}else{
				//将关键字push到数组之中
				var arr = [];
				if(sets.divFlag){
					arr = str.split(sets.divStr);	
				}else{
					arr.push(str);	
				}
			}
			var v_html = t.html();
			//删除注释
			v_html = v_html.replace(/<!--(?:.*)\-->/g,"");
			
			//将HTML代码支离为HTML片段和文字片段，其中文字片段用于正则替换处理，而HTML片段置之不理
			var tags = /[^<>]+|<(\/?)([A-Za-z]+)([^<>]*)>/g;
			var a = v_html.match(tags), test = 0;
			$.each(a, function(i, c){
				if(!/<(?:.|\s)*?>/.test(c)){//非标签
					//开始执行替换
					$.each(arr,function(index, con){
						if(con === ""){return;}
						var reg = new RegExp($.regTrim(con), "g");
						if(reg.test(c)){
							//正则替换
							c = c.replace(reg,"♂"+con+"♀");
							test = 1;
						}
					});
					c = c.replace(/♂/g,"<span rel='mark' "+clStr+">").replace(/♀/g,"</span>");
					a[i] = c;
				}
			});
			//将支离数组重新组成字符串
			var new_html = a.join("");
			$(this).html(new_html);
			if(test === 0 && sets.nullReport){
				//alert("没有搜索结果");	
				return false;
			}
			//执行回调函数
			sets.callback();
		});
	};
})(jQuery);

// 筛选品牌和分类商品时通用方法
function ChoiceGoods() {
	var _this = this;
	var dt, bg;
	// 隱藏列表
	this.hide = function() {
		aju.removeAll([dt,bg,$('.tip-yellow')]);
		$('#ajaxBg').remove();
		$('#ajaxClose').remove();
	};
	function search(q, bid, cid, callbackAddItem) {
		if(bid==undefined) {
			bid='';
		}
		if(cid==undefined) {
			cid='';
		}
		//alert('callbackAddItem: ' + callbackAddItem);
		bg = aju.ajaxBg(function() {
			aju.setOffsetDown(10);
			aju.setOffsetRight(10);
			var url = '/a/ajax/sell/goodsSelector?r=' + new Date() + "&q="+q+"&bid="+bid+"&cid="+cid;
			$.get(url, function(data){
				dt = aju.ajaxData().css({'width':'90%','height':'auto', 'padding-top':'30px'});
					dt.html(data);
					aju.positionCenter(dt);
					// 显示关闭按钮并绑定关闭时间
					aju.ajaxClose(dt).click(function(){
						_this.hide();
					});
					// 显示商品列表后绑定选定事件
					dt.find('tr').mouseover(function(){
						$(this).css({'background':'#ffff88'}).find('td').css('color','#000');
					}).mouseout(function(){
						$(this).css('background','').find('td').css('color','#333');
					}).click(function(){
						var id = $(this).attr('id');
						if(callbackAddItem != undefined && id != undefined) {
							//alert(id);
							callbackAddItem(id);
						}
					});
			});
		});
		$('body').keydown(function(event){
			if(KEY.ESC == event.keyCode) {
				_this.hide();
			}
		});
	};
	//
	// 显示品牌和种类的时候绑定搜索事件
	function bindSearchEvent(callbackAddItem) {
		$('#bc_q').keydown(function(event){
			if(KEY.ENTER == event.keyCode) {
				var q = $('#bc_q').val();
				_this.hide();
				search(q, null, null, callbackAddItem);
			}
		}).focus();
		$('#bc_button').click(function(){
			var q = $('#bc_q').val();
			_this.hide();
			search(q, null, null, callbackAddItem);
		});
	};
	//
	function bindEvent(callbackAddItem) {
		_this.bindLiClick(function(brandId, categoryId){
			_this.hide();
			search('', brandId, categoryId, callbackAddItem);
		}, function(){
			callbackAddItem();
		});
	};
	this.showGoods = function(callbackAddItem) {
		var q = $('#goodsKey').val();
		if(q!=undefined && q.length>0) {
			search(q,null,null,callbackAddItem);
			return ;
		}
		bg = aju.ajaxBg(function() {
			aju.setOffsetDown(20);
			aju.setOffsetRight(10);
			var url = '/a/ajax/sell/goodsSelector?r=' + new Date();
			$.get(url, function(data){
					dt = aju.ajaxData().css('width','80%');
					dt.html(data);
					aju.positionCenter(dt);
					// 显示关闭按钮并绑定关闭事件
					aju.ajaxClose(dt).click(function(){
						_this.hide();
					});
					// 根据品牌种类筛选商品  绑定点击事件
					bindEvent(callbackAddItem);
					$(".letter li").mouseover(function(){
						$(this).removeClass('lichk');
						$(this).addClass("lichk");
					}).mouseout(function(){
						
					});
					$('#letterBrand li').bind('click', function(){
						var val = $(this).html();
						if(val == '全部') {
							val = '';
						}
						$('#brand_chked').val(val);
						$('#letterBrand li').each(function(){
							if(val!=$(this).text()){
								$(this).removeClass('lichk');
							}
						});
						$.get('/a/ajax/sell/brand?letterBrand=' + val, function(data){
							$('#brand_dd').html(data);
							bindEvent(callbackAddItem);
						});
					}).mouseout(function(){
						if($('#brand_chked').val()!=$(this).text()){
							$(this).removeClass('lichk');
						}
					});
					$('#letterCategory li').click(function(){
						var val = $(this).html();
						if(val == '全部') {
							val = '';
						}
						$('#category_chked').val(val);
						$('#letterCategory li').each(function(){
							if(val!=$(this).text()){
								$(this).removeClass('lichk');
							} 
						});
						$.get('/a/ajax/sell/category?letterCategory=' + val, function(data){
							$('#category_dd').html(data);
							bindEvent(callbackAddItem);
						});
					}).mouseout(function(){
						if($('#category_chked').val()!=$(this).text()){
							$(this).removeClass('lichk');
						}
					});
					// 显示品牌和种类的时候绑定搜索事件
					bindSearchEvent(callbackAddItem);
			});
		});
	};
	this.bindLiClick = function(callback, callbackAddItem) {
		$("#ajaxData li").bind('click', function(){
			var id = $(this).attr('id');
			if(id == undefined) {
				return ;
			}
			if(id.indexOf('brand') != -1) {
				$("#brand_dd li").removeClass('clked');
				id = id.replace('brand_', '');
				$('#brand_id').val(id);
			}
			else if(id.indexOf('category') != -1) {
				$("#category_dd li").removeClass('clked');
				id = id.replace('category_', '');
				$('#category_id').val(id);
			}
			var categoryId = $('#category_id').val();
			var brandId = $('#brand_id').val();
			if(categoryId!=undefined 
					&& brandId!=undefined 
					&& categoryId.length > 0 
					&& brandId.length > 0) 
			{
				callback(brandId,categoryId, callbackAddItem);
			}	
			$(this).addClass("clked");
		});
	};
}
var choiceGoods = new ChoiceGoods();
//

function Payment() {
	var _this = this;
	var bg, dt;
	function hide() {
		aju.removeAll([ dt, bg, $('.tip-yellow') ]);
		$('#ajaxClose').remove();
	};
	$(document).keydown(function(){
		if(event.keyCode == KEY.ESC) {
			hide();
		}
	});
	this.dopay = function(btn, callback) {
		$(btn).val('正在支付，请稍后...').attr('disabled', 'disabled');
		var id = $('#id').val();
		var cash = $('#cash').val();
		var useBalance=$('#useBalance').is(':checked');
		$.ajax({
			url:'/a/ajax/customer/payment/save'
			,type:'POST'
			,data:{id:id,cash:cash,useBalance:useBalance}
			,success:function(data){
				$(btn).val('支付完成');
				var json = $.parseJSON(data);
				var isChecked = json.data.isChecked;
				if(isChecked) {
					$('#isChecked_'+json.data.id).html('<span class="paymentClear">清</span>');
					alert('支付完成，本次帐单已经结清！');
				} else {
					alert('支付完成，本次帐单尚未结清！！！');
				}
				hide();
				if(callback) {
					callback();
				}
			}
			,error:function() {
				alert('发生意外错误，请联系管理员！');
			}
		});
	};
	this.showForm = function(id, callback) {
		var r = new Date();
		$.ajax({
			url:'/a/ajax/customer/payment/form?r='+r
			,type:'GET'
			,data:{id:id,r:r}
			,success:function(data){
				bg = aju.ajaxBg(function() {
					aju.setOffsetDown(200);
					aju.setOffsetRight(10);
					dt = aju.ajaxData().css({
						'width' : '600',
						'height' : '360'
					});
					dt.html(data);
					aju.positionCenter(dt);
					// 显示关闭按钮并绑定关闭事件
					aju.ajaxClose(dt).click(function() {
							hide();
					});
					var balance = parseFloat($('.balance').html());
					var realPayables = parseFloat($('.realPayables').html());
					var sumPaid = parseFloat($('.sumPaid').html());
					$('#cash').focus();
					var useBalance=$('#useBalance').is(':checked');
					$('#useBalance').click(function(){
						var n = (balance - realPayables + sumPaid);
						var used = $(this).is(':checked');
						if(used) {
							$('#cash').css({'display':'none'});
							if(n>0) {
								$('#cash').val('0');
								$('#_cash').html('<span class="green">支付完成后帐户可用余额：' + n + "</span>");
							} else {
								$('#_cash').html('<span class="red">帐户余额不足，不能完成支付！</span>');
								$('#payBtn').attr('disabled', 'disabled');
							}
						} else {
							$('#cash').val(realPayables-sumPaid);
							$('#cash').css({'display':''});
							$('#_cash').html('<span class="green"></span>');
							$('#payBtn').removeAttr('disabled');
						}
					});
					// bind do
					$('#payBtn').click(function(){
						_this.dopay(this, callback);
					});
				});
			}
		});
	};
}
var payment = new Payment();